﻿using System;
using System.Reflection;
using Shell.PocoDot.Attributes;
using Shell.PocoDot;
using Shell.PocoDot.Configurations;

namespace Shell.DomainDot
{
    static class DomainInjectHelper
    {
        public static PropertyInfo GetMatchedProperty(Type baseType, Type matchingGenericTypeDefinition)
        {
            if (matchingGenericTypeDefinition.IsGenericType)
            {
                foreach (var p in baseType.GetProperties())
                {
                    var propType = p.PropertyType;
                    if (propType.IsGenericType)
                    {
                        if (propType.GetGenericTypeDefinition() == matchingGenericTypeDefinition)
                        {
                            return p;
                        }
                    }
                }
            }
            return null;
        }

        public static Type GetPocoType(PropertyInfo domainSegment)
        {
            var pocoBaseType = typeof(PocoDotBase);
            var t = domainSegment.PropertyType;

            if (pocoBaseType.IsAssignableFrom(t))
            {
                return t;
            }
            else if (t.IsGenericType)
            {
                var ts = t.GetGenericArguments();
                Type pocoType = null;
                foreach (var targ in ts)
                {
                    if (pocoBaseType.IsAssignableFrom(targ))
                    {
                        if (pocoType == null)
                        {
                            pocoType = targ;
                        }
                        else
                        {
                            //TODO
                        }
                    }
                }
                return pocoType;
            }
            return null;
        }
    }
}
